<template>
  <div class="ai-assistant-page">
    <navigation-bar />

    <!-- Breadcrumb -->
    <div class="breadcrumb">
      <div class="breadcrumb-content">
        <router-link to="/">首页</router-link>
        <span>/</span>
        <span>AI穿搭助手</span>
      </div>
    </div>
    <div class="main-container">
      <div class="chat-container">
        <div class="chat-header">
          <div class="ai-avatar">
            <robot-outlined />
          </div>
          <div class="ai-info">
            <div class="ai-name">StyleFit AI</div>
            <div class="ai-status">
              <span class="status-dot"></span>
              <span>在线，随时为您提供穿搭建议</span>
            </div>
          </div>
        </div>

        <div class="chat-messages" ref="chatMessagesRef">
          <template v-for="(message, index) in chatMessages" :key="index">
            <div class="message" :class="{ user: message.isUser }" v-if="!message.isTyping">
              <div class="message-avatar">
                <robot-outlined v-if="!message.isUser" />
                <user-outlined v-else />
              </div>
              <div class="message-content" v-if="!message.clothes">
                <div v-html="formatMessage(message.content)"></div>
              </div>
              <div class="message-content clothes-message" v-else>
                <div v-html="formatMessage(message.content)"></div>
                <div class="clothes-list">
                  <ai-clothes-card 
                    v-for="(clothes, clothesIndex) in message.clothes" 
                    :key="clothesIndex"
                    :item="{
                      image: clothes.imageUrl,
                      name: clothes.name,
                      description: clothes.description,
                      categoryId: clothes.categoryId,
                      productUrl: clothes.productUrl,
                      price: clothes.price
                    }"
                    @click="() => window.open(clothes.productUrl, '_blank')"
                  />
                </div>
              </div>
            </div>
            <div class="message" v-else>
              <div class="message-avatar">
                <robot-outlined />
              </div>
              <div class="message-content typing">
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
              </div>
            </div>
          </template>
        </div>

        <div class="chat-input">
          <div class="input-container">
            <textarea 
              class="input-field" 
              v-model="messageInput" 
              placeholder="输入你的问题，比如：建议我参加明天的面试该怎么穿..." 
              rows="1"
              @keypress.enter.prevent="sendMessage"
              @input="adjustTextareaHeight"
            ></textarea>
            <button class="send-button" @click="sendMessage" title="发送">
              ✈
            </button>
          </div>
        </div>
      </div>

      <div class="suggestion-panel">
        <h3 class="panel-title">你可以这样问我</h3>
        <div class="suggestion-list">
          <div class="suggestion-item" 
            v-for="(suggestion, index) in suggestions" 
            :key="index"
            @click="usePrompt(suggestion)">
            {{ suggestion }}
          </div>
        </div>
      </div>
    </div>

    <page-footer />
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick } from 'vue'
import {
  RobotOutlined,
  UserOutlined
} from '@ant-design/icons-vue'
import NavigationBar from '@/components/layout/NavigationBar.vue'
import PageFooter from '@/components/layout/PageFooter.vue'
import AIClothesCard from '@/components/AIClothesCard.vue'

export default defineComponent({
  name: 'AIAssistantPage',
  components: {
    RobotOutlined,
    UserOutlined,
    NavigationBar,
    PageFooter,
    'ai-clothes-card': AIClothesCard
  },
  setup() {
    const messageInput = ref('')
    const chatMessages = ref([])
    const chatMessagesRef = ref(null)
    
    const suggestions = [
      '我想要浪漫的约会搭配。',
      '明天有个重要的工作面试，建议穿什么？',
      '帮我搭配一套适合周末约会的穿搭。',
      '这个季节适合什么样的衣服搭配？',
      '我的衣橱里有这些衣服，帮我搭配一下。',
      '推荐一些显高显瘦的穿搭技巧。',
      '如何搭配职场通勤装？'
    ]

    // 初始化欢迎消息
    onMounted(() => {
      chatMessages.value.push({
        isUser: false,
        content: `你好！我是你的AI穿搭助手。我可以：
• 根据场合推荐合适的穿搭
• 分析你的衣橱提供搭配建议
• 解答各种穿搭相关问题
• 提供个性化的时尚建议

请告诉我你需要什么帮助？`
      })
    })

    const scrollToBottom = async () => {
      await nextTick()
      if (chatMessagesRef.value) {
        chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
      }
    }

    const formatMessage = (content) => {
      return content.replace(/\n/g, '<br>')
    }

    const adjustTextareaHeight = (event) => {
      const textarea = event.target
      textarea.style.height = 'auto'
      textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
    }

    const usePrompt = (prompt) => {
      messageInput.value = prompt
      // 自动聚焦输入框
      const textarea = document.querySelector('.input-field')
      if (textarea) {
        textarea.focus()
      }
    }

    const sendMessage = async () => {
      const content = messageInput.value.trim()
      if (!content) return

      // 添加用户消息
      chatMessages.value.push({
        isUser: true,
        content
      })

      // 清空输入框
      messageInput.value = ''
      const textarea = document.querySelector('.input-field')
      if (textarea) {
        textarea.style.height = '52px'
      }

      // 滚动到底部
      await scrollToBottom()

      // 显示AI正在输入
      chatMessages.value.push({
        isTyping: true
      })
      await scrollToBottom()

      try {
        // 调用风格分析API
        const response = await fetch('api/style-analyse/analyze', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify({
            text: content
          })
        })

        if (!response.ok) {
          throw new Error(`API请求失败: ${response.status} ${response.statusText}`)
        }

        const result = await response.json()
        
        // 移除正在输入状态
        chatMessages.value = chatMessages.value.filter(msg => !msg.isTyping)
        
        if (result.success && result.data) {
          // 检查是否包含衣服ID
          const lastLine = result.data[result.data.length - 1]
          const clothesIds = lastLine.split(',').map(id => id.trim()).filter(id => !isNaN(id))
          
          // 构建响应消息
          let responseContent = ''
          
          if (clothesIds.length > 0) {
            // 处理包含衣服ID的响应
            responseContent = '根据您的需求，我为您推荐以下搭配：\n\n'
            
            // 获取每件衣服的详细信息
            const clothesPromises = clothesIds.map(async (id) => {
              try {
                const clothesResponse = await fetch(`api/clothes-one/${id}`, {
                  method: 'GET',
                  headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                  }
                })
                if (!clothesResponse.ok) {
                  throw new Error(`获取衣物信息失败: ${clothesResponse.status}`)
                }
                const clothesData = await clothesResponse.json()
                return clothesData.data
              } catch (error) {
                console.error(`获取衣物 ${id} 信息失败:`, error)
                return null
              }
            })

            const clothesDetails = await Promise.all(clothesPromises)
            
            // 过滤掉获取失败的衣服
            const validClothes = clothesDetails.filter(item => item !== null)
            
            chatMessages.value.push({
              isUser: false,
              content: responseContent,
              clothes: validClothes
            })
          } else {
            // 处理普通对话响应
            // 从响应中提取实际回答部分（跳过日志信息）
            const answerIndex = result.data.findIndex(line => line.startsWith('Answer:'))
            if (answerIndex !== -1) {
              responseContent = result.data.slice(answerIndex + 1).join('\n')
            } else {
              responseContent = result.data.join('\n')
            }

            chatMessages.value.push({
              isUser: false,
              content: responseContent
            })
          }
        } else {
          throw new Error(result.errorMsg || '分析失败')
        }
      } catch (error) {
        console.error('API调用错误:', error)
        
        // 移除正在输入状态
        chatMessages.value = chatMessages.value.filter(msg => !msg.isTyping)
        
        // 添加错误消息
        chatMessages.value.push({
          isUser: false,
          content: `抱歉，服务出现了一些问题：\n${error.message}\n\n请稍后再试。`
        })
      }
      
      await scrollToBottom()
    }

    return {
      messageInput,
      chatMessages,
      chatMessagesRef,
      suggestions,
      adjustTextareaHeight,
      usePrompt,
      sendMessage,
      formatMessage
    }
  }
})
</script>

<style scoped>
.ai-assistant-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

.main-container {
  max-width: 100%;
  margin: 84px auto 2rem;
  padding: 0 6rem;
  display: flex;
  justify-content: space-between;
  gap: 2rem;
  height: calc(100vh - 120px);
}

.chat-container {
  flex: 1;
  max-width: 1200px;
  min-width: 900px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  padding: 1rem;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex-shrink: 0;
}

.ai-avatar {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: linear-gradient(135deg, #3498db, #2ecc71);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1rem;
}

.ai-info {
  flex: 1;
  min-width: 0;
}

.ai-name {
  font-size: 0.95rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.25rem;
}

.ai-status {
  font-size: 0.8rem;
  color: #64748b;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #10b981;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  min-height: 0;
}

.message {
  display: flex;
  gap: 0.75rem;
  max-width: 85%;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 28px;
  height: 28px;
  border-radius: 4px;
  background: #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #64748b;
  font-size: 0.85rem;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background: #3498db;
  color: white;
}

.message-content {
  background: #f8fafc;
  padding: 0.75rem 1rem;
  border-radius: 6px;
  color: #1e293b;
  font-size: 0.85rem;
  line-height: 1.5;
}

.message.user .message-content {
  background: #3498db;
  color: white;
  border-radius: 6px;
}

.chat-input {
  padding: 1rem;
  border-top: 1px solid #e2e8f0;
  flex-shrink: 0;
}

.input-container {
  display: flex;
  gap: 0.75rem;
  position: relative;
}

.input-field {
  flex: 1;
  padding: 0.75rem;
  padding-right: 2.5rem;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.85rem;
  resize: none;
  height: 44px;
  transition: all 0.3s;
  line-height: 1.5;
}

.input-field:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
}

.send-button {
  position: absolute;
  right: 0.5rem;
  bottom: 0.5rem;
  background: #3498db;
  color: white;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 18px;
  transform: rotate(45deg);
}

.send-button:hover {
  background: #2980b9;
  transform: rotate(45deg) scale(1.05);
}

.suggestion-panel {
  width: 320px;
  margin-right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1rem;
  height: fit-content;
  flex-shrink: 0;
}

.panel-title {
  font-size: 0.95rem;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.75rem;
}

.suggestion-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.suggestion-item {
  padding: 0.5rem 0.75rem;
  background: #f8fafc;
  border-radius: 4px;
  font-size: 0.8rem;
  color: #64748b;
  cursor: pointer;
  transition: all 0.3s;
  line-height: 1.4;
}

.suggestion-item:hover {
  background: #f1f5f9;
  color: #1e293b;
  transform: translateX(4px);
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #e2e8f0;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #cbd5e1;
}

.message-content.typing {
  padding: 0.75rem;
}

.typing-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #94a3b8;
  margin: 0 2px;
  animation: typing 1.4s infinite;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-3px);
  }
}

.message-content {
  white-space: pre-line;
}

.clothes-card {
  margin-bottom: 0.75rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.clothes-content {
  display: flex;
  gap: 0.75rem;
  padding: 0.75rem;
}

.clothes-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.clothes-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.clothes-info {
  flex: 1;
  min-width: 0;
}

.clothes-info h4 {
  margin: 0 0 0.25rem;
  font-size: 0.9rem;
  color: #1e293b;
}

.clothes-price {
  color: #ef4444;
  font-weight: 600;
  margin: 0 0 0.25rem;
  font-size: 0.85rem;
}

.clothes-description {
  color: #64748b;
  font-size: 0.8rem;
  margin: 0 0 0.25rem;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.clothes-link {
  display: inline-block;
  color: #3498db;
  text-decoration: none;
  font-size: 0.8rem;
  transition: color 0.3s;
}

.clothes-link:hover {
  color: #2980b9;
  text-decoration: underline;
}

.clothes-message {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1rem;
}

.clothes-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-top: 1rem;
  padding: 1rem;
}
</style>
